//
//  PerInfoController.m
//  Estate
//
//  Created by heyong on 16/6/23.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#import "PerInfoController.h"
#import "PerInfoCell.h"
#import "DoubleLabCell.h"
#import "UpdatePwdController.h"
@interface PerInfoController ()
{
    NSString *gender;
    UIImage *image;
}
@end

@implementation PerInfoController

- (UITableView *)tableView{
    if(_tableView==nil){
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 20, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT-20)];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        _tableView.bounces=NO;
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
    self.tableView.translatesAutoresizingMaskIntoConstraints=NO;
    self.tableView.tableFooterView=[[UIView alloc]initWithFrame:CGRectZero];
    [self.tableView registerNib:[UINib nibWithNibName:@"PerInfoCell" bundle:nil] forCellReuseIdentifier:@"PerInfoCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"DoubleLabCell" bundle:nil] forCellReuseIdentifier:@"labCell"];
    self.title=@"个人信息";
    self.tableView.backgroundColor=[UIColor colorWithRed:0.95 green:0.96 blue:0.96 alpha:1.00];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section==0){
        return 5;
    }else
        return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section==0){
        return 0;
    }else
        return 10;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section==0){
        if(indexPath.row==0){
            return 60;
        }else{
            return 44;
        }
    }else
        return 44;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    long section=indexPath.section;
    long row=indexPath.row;
    if(section==0){
        if(row==0){
            //            PerInfoCell *cell1=[tableView dequeueReusableCellWithIdentifier:@"PerInfoCell" forIndexPath:indexPath];
            ////            cell1.txImageView.image=[UIImage imageNamed:@"touxiang_de"];
            //            cell1.selectionStyle=UITableViewCellSelectionStyleNone;
            //            return cell1;
            
            PerInfoCell *cell1=[tableView dequeueReusableCellWithIdentifier:@"PerInfoCell" forIndexPath:indexPath];
            
            if(image){
                cell1.txImageView.image=image;
            }
            else{
                [LSHttpTool checkNetWork:^(NSString *status) {
                    if([status isEqualToString:@"0"]){
                        NSString *urlStr=[NSString stringWithFormat:@"%@/%@",API_HOST,self.headUrl];
                        [cell1.txImageView sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:[UIImage imageNamed:@"touxiang_de"] options:SDWebImageRefreshCached];
                    }else{
                        NSString *urlStr=[NSString stringWithFormat:@"%@/%@&r=%@",API_HOST,self.headUrl,[LSUtility getCurrentDateString]];
                        [cell1.txImageView sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:[UIImage imageNamed:@"touxiang_de"] options:SDWebImageRefreshCached];
                    }
                }];
            }
            
            return cell1;
        }else if(row==1){
            
            DoubleLabCell *cell=[tableView dequeueReusableCellWithIdentifier:@"labCell" forIndexPath:indexPath];
            //            NSString *name=[LSUtility getuserIdByUserName:USERID][@"REAL_NAME"];
            NSString *name=DEF_PERSISTENT_GET_OBJECT(@"realname");
            [cell setTitle:@"姓名" AndDetail:name];
            return cell;
        }else if (row==2){
            
            DoubleLabCell *cell=[tableView dequeueReusableCellWithIdentifier:@"labCell" forIndexPath:indexPath];
            NSString *sexNum=[LSUtility getuserIdByUserName:USERID][@"SEX"];
            if([sexNum isEqualToString:@"0"]){
                gender=@"女";
            }else
            {
                gender=@"男";
                
            }
            [cell setTitle:@"性别" AndDetail:gender];
            
            cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            return cell;
        }else if (row==3){
            DoubleLabCell *cell=[tableView dequeueReusableCellWithIdentifier:@"labCell" forIndexPath:indexPath];
            NSString *unitId=[LSUtility getuserIdByUserName:USERID][@"UNIT"];
            NSString *unitName=[LSUtility getUnitNameByUnitIdPro:unitId][@"ORGNAME"];
            [cell setTitle:@"部门" AndDetail:unitName==nil?@"无":unitName];
            cell.titleWconstraint.constant=DEF_SCREEN_WIDTH *0.2;
            cell.detailWconstraint.constant=DEF_SCREEN_WIDTH *0.7;
            return cell;
        }else{
            DoubleLabCell *cell=[tableView dequeueReusableCellWithIdentifier:@"labCell" forIndexPath:indexPath];
            cell.titleWconstraint.constant=DEF_SCREEN_WIDTH *0.2;
            cell.detailWconstraint.constant=DEF_SCREEN_WIDTH *0.7;
            [cell setTitle:@"职位" AndDetail:DEFISNUL(self.role)];
            return cell;
        }
    }else{
        
        UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"acell"];
        if(!cell){
            cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"acell"];
        }
        cell.textLabel.text=@"修改密码";
        cell.textLabel.font=[UIFont systemFontOfSize:15.];
        cell.textLabel.textColor=[UIColor colorWithRed:0.44 green:0.45 blue:0.45 alpha:1.00];
        cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        return cell;
    }
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    long section=indexPath.section;
    long row=indexPath.row;
    if(section==0){
        if(row==0){
            [LSHttpTool checkNetWork:^(NSString *status) {
                if([status isEqualToString:@"0"]){
                    [LSUtility showToastWithMessage:@"请先连接网络!" inView:self.view Andtime:1.8];
                }else{
                    [self setup];
                }
            }];
        }
        //        if(row==2){
        //        }
    }
    if(section==1){
        UpdatePwdController *upPwd=[[UpdatePwdController alloc]init];
        [self.navigationController pushViewController:upPwd animated:YES];
    }
}

/*
 *  此方法让cell横线置顶
 */
-(void)viewDidLayoutSubviews {
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])  {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPat{
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
}

#pragma mark -修改性别
-(void)changeGender{
    //                UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //                UIAlertAction *actionMan = [UIAlertAction actionWithTitle:@"男" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
    //                    gender=@"男";
    //                    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:2 inSection:0];
    //                    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
    //                }];
    //                //设置颜色
    //                 [actionMan setValue:[UIColor colorWithRed:0.00 green:0.56 blue:0.51 alpha:1.00] forKey:@"_titleTextColor"];
    //                [alert addAction:actionMan];
    //
    //                UIAlertAction *actionWoMan = [UIAlertAction actionWithTitle:@"女" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
    //                    gender=@"女";
    //                    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:2 inSection:0];
    //                    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
    //                }];
    //                [actionWoMan setValue:[UIColor colorWithRed:0.00 green:0.56 blue:0.51 alpha:1.00] forKey:@"_titleTextColor"];
    //                [alert addAction:actionWoMan];
    //
    //                UIAlertAction *actionCance = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
    //                    NSLog(@"取消");
    //                }];
    //                [actionCance setValue:[UIColor colorWithRed:0.00 green:0.56 blue:0.51 alpha:1.00] forKey:@"_titleTextColor"];
    //                [alert addAction:actionCance];
    //
    //                [self presentViewController:alert animated:YES completion:nil];
}


#pragma mark -更新头像
- (void)setup
{
    UIAlertController *aler=[UIAlertController alertControllerWithTitle:@"更换头像" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //从相机选取
    UIAlertAction *album=[UIAlertAction actionWithTitle:@"从相册选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *picker=[[UIImagePickerController alloc]init];
        
        //不能选择图片
        picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        picker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString*)kUTTypeImage,nil];
        //        picker.mediaTypes=[UIImagePickerController availableMediaTypesForSourceType:picker.sourceType];
        
        picker.allowsEditing=YES;
        picker.delegate=self;
        [self presentViewController:picker animated:YES completion:nil];
    }];
    //从相机选取
    UIAlertAction *camera=[UIAlertAction actionWithTitle:@"相机拍摄" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *picker=[[UIImagePickerController alloc]init];
        picker.sourceType=UIImagePickerControllerSourceTypeCamera;
        picker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString*)kUTTypeImage,nil];
        picker.allowsEditing=YES;
        picker.delegate=self;
        [self presentViewController:picker animated:YES completion:nil];
        
    }];
    
    UIAlertAction *cancl=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [aler addAction:cancl];
    [aler addAction:album];
    [aler addAction:camera];
    [self presentViewController:aler animated:YES completion:nil];
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    
    image=[info objectForKey:UIImagePickerControllerEditedImage];
    
    NSLog(@"info%@",info);
    //上传头像
    NSMutableDictionary *parame=[NSMutableDictionary dictionary];
    [parame setObject:USERID forKey:@"userId"];
    
    [LSHttpTool upload:URL_UPDATA_HEADPHOTO parameters:parame andFileName:@"tx.png" andImage:image progress:^(id uploadProgress) {
        //        NSProgress *pro=(NSProgress *)uploadProgress;
        //        NSLog(@"进度：%lf",1.0 *pro.completedUnitCount / pro.totalUnitCount);
    } success:^(id success) {
        NSString *code=success[@"code"];
        if([code isEqualToString:@"1"]){
            //        self.userView.headImageView.image=image;
            NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
            PerInfoCell *cell=[self.tableView cellForRowAtIndexPath:indexPath];
            cell.txImageView.image=image;
            //            cell.txImageView.image=[UIImage imageNamed:@"all_click"];
            //            self.userModel.headUrl=success[@""];
            [self.tableView reloadData];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"changeHeadImage" object:nil];
            
            
        }else{
            [LSUtility showToastWithMessage:@"头像更改失败，请稍后重试。" inView:self.view Andtime:1.2];
        }
        
        
    } failure:^(NSError *error) {
        [MBProgressHUD showError:@"修改头像失败" toView:self.view];
    }];
    
    //选取完图片之后关闭视图
    [self dismissViewControllerAnimated:YES completion:nil];
    
}
//点击取消
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

@end
